package com.atguigu.flink.window;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import com.atguigu.flink.utils.MyUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;

import java.util.List;

/**
 * Created by Smexy on 2023/1/30
 * 
 *      分类的规则三种
 *          1.是否keyBy
 *          2.基于时间还是个数
 *                  个数: 处理函数中就有 GlobalWindow
 *          3.特性(滚动|滑动|会话)
 *          
 *       keyBy,基于个数的 滚动|滑动
 *
 *    -----------
 *      不keyBy :  xxxAll
 *      keyBy:     xxx
 *
 *      时间:  window
 *      个数:  countWindow
 *
 *
 */
public class Demo4_KeyByCountWindow
{
    public static void main(String[] args) {

        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 3333);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

                env
                   .socketTextStream("hadoop103", 8888)
                   .map(new WaterSensorMapFunction())
                   // 每个key都有自己的窗口
                   .keyBy(WaterSensor::getId)
                   // 3个元素的滚动窗口 size = slide = 3
                   .countWindow(3)
                   //<IN, OUT, KEY, W extends Window>
                   .process(new ProcessWindowFunction<WaterSensor, String, String, GlobalWindow>()
                   {
                       @Override
                       public void process(String key, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {

                           List<WaterSensor> list = MyUtil.parseList(elements);
                           out.collect(key +":"+list.toString());

                       }
                   })
                   .print();

        
                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
        
    }
}
